package logic

import (
	"context"
	"fmt"
	"home-manage/cache"
	"home-manage/model"

	"home-manage/homerpc/homerpc"
	"home-manage/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordLogic {
	return &PasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordLogic) Password(in *homerpc.PasswordRequest) (*homerpc.PasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	model.DB.Debug().Where("tel", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户未注册无法修改")
	}
	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if in.SendSms != s {
		return nil, fmt.Errorf("验证码错误请重新输入")
	}
	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("两次密码不一致请重新输入")
	}
	if user.Password == in.Newpassword {
		return nil, fmt.Errorf("新密码与旧密码一致")
	}
	user.Password = in.Newpassword
	model.DB.Debug().Updates(&user)
	return &homerpc.PasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
